

package com.example.petplanet.util;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.Callback;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.example.petplanet.config.AliyunConfig;

import java.io.InputStream;
import java.util.Date;

public class OSSUtil {

    // Endpoint以华东2（福州）为例，其它Region请按实际情况填写。

    // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
    //EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

    // 填写Bucket名称，例如examplebucket。

    // 填写Bucket所在地域。以华东6（福州）为例，Region填写为cn-fuzhou。

    //!!!!!!!!!!!!!!!!!!!!这里的in传入的参数 先将MultipartFile对象转为数据流即调用.getInputStream()
    public static String uploadFileToAli(String catalog,String suffixName,String objectName, String uploadId, Long userId, InputStream in, AliyunConfig aliyunConfig) throws Exception {

        OSS ossClient=getOSSObject(aliyunConfig);

        String url="";
        String bucketName=aliyunConfig.getBucketName();
        String finalName=catalog+'/'+objectName+suffixName;



        //本地测试不回调
        String callbackUrl = "http://47.122.44.26:8083/content/callBack";

        try {
//             填写字符串。这是传入的数据
//            String content = "Hello OSS，你好世界";

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, finalName,in);

            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);




            //本地测试注释
            // 上传回调参数。
            Callback callback = new Callback();
            callback.setCallbackUrl(callbackUrl);
            //（可选）设置回调请求消息头中Host的值，即您的服务器配置Host的值。
            // callback.setCallbackHost("yourCallbackHost");
            //设置发起回调请求的自定义参数，由Key和Value组成，Key必须以x:开始。
            callback.addCallbackVar("x:userId",userId.toString());
            callback.addCallbackVar("x:uploadId",uploadId);
            // 设置发起回调时请求body的值。
            callback.setCallbackBody("{\\\"bucket\\\":${bucket},\\\"object\\\":${object},\\\"size\\\":${size},\\\"etag\\\":${etag},\\\"userId\\\":${x:userId},\\\"uploadId\\\":${x:uploadId},\\\"clientIp\\\":${x:clientIp}}");
//            callback.setCallbackBody("{\\\"mimeType\\\":${mimeType},\\\"size\\\":${size}}");
            // 设置发起回调请求的Content-Type。
            callback.setCalbackBodyType(Callback.CalbackBodyType.JSON);

            putObjectRequest.setCallback(callback);


            // 上传字符串。
            PutObjectResult result = ossClient.putObject(putObjectRequest);

            //url组成:https://bucket名称.区域节点/objectName
            //url="https://"+bucketName+"."+endpoint.substring(endpoint.lastIndexOf("/")+1)+"/"+objectName;
            url=ossClient.generatePresignedUrl(bucketName,finalName,new Date(System.currentTimeMillis()+3600*1000)).toString();
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return url;
    }

    public static void deleteFileFromAli(AliyunConfig aliyunConfig,String objectName) throws Exception{

        OSS ossClient=getOSSObject(aliyunConfig);
        String bucketName=aliyunConfig.getBucketName();//段俊给钱了就多几个bucket 用case

        try {
            if (ossClient.doesObjectExist(bucketName, objectName)) {
                ossClient.deleteObject(bucketName, objectName);
                System.out.println("文件删除成功：" + objectName);
            } else {
                throw new RuntimeException("文件不存在:"+objectName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }finally {
            ossClient.shutdown();
        }
    }

    public static OSS getOSSObject(AliyunConfig aliyunConfig){
        String accessKeyId=aliyunConfig.getAccessKeyId();
        String accessKeySecret=aliyunConfig.getAccessKeySecret();
        String endpoint=aliyunConfig.getEndpoint();
        String bucketName=aliyunConfig.getBucketName();
        String region=aliyunConfig.getRegion();

        // 创建OSSClient实例。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        return OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(new DefaultCredentialProvider(accessKeyId, accessKeySecret))
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();
    }
}

